package com.lcf.app.minio.controller;

import com.lcf.app.minio.service.MinioService;
import io.minio.GetObjectResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

@RestController
@RequestMapping("minio")
public class MinioController {

    private static final String BUCKET_NAME = "bucket-one"; // 桶名称

    @Autowired
    private MinioService minioService;

    @RequestMapping("upload")
    public String upload(MultipartFile file) {
        try {
            minioService.upload(BUCKET_NAME, file.getOriginalFilename(), file);
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
        return "ok";
    }

    @RequestMapping("download")
    public void download(String object, HttpServletResponse response) throws Exception {
        GetObjectResponse download = minioService.download(BUCKET_NAME, object);
        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(download.object(), "UTF-8"));
        IOUtils.copy(download, response.getOutputStream());
    }

}
